package studio.xiaoyun.web;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class JsonAdapter extends JsonSerializer<HttpResponse> {

	@Override
	public void serialize(HttpResponse httpResponse, JsonGenerator jsonGenerator,
			SerializerProvider serializerProvider) throws IOException,
			JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();  
		mapper.setSerializationInclusion(Include.NON_NULL);
		SimpleModule module = new SimpleModule();  
		module.addSerializer(Date.class, new DateSerializer());  
		mapper.registerModule(module);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", httpResponse.getTotal());
		map.put("rows", httpResponse.getRows());
		if(httpResponse.getError() != null){
			map.put("error", httpResponse.getError());
		}
		String str = mapper.writeValueAsString(map);
		jsonGenerator.writeRaw(str);
	}

}
